# -*- coding: utf-8 -*-
import hashlib
import time
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://pay.wxhsme.cn/gate/pay/tran'
# witch 银联
APP_CONF = {
    '100110089991188': {
        'API_KEY': 'dGO6yNwLruNJUzwjyHm3ng==',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


# 支付渠道
# alipay_qr - 支付宝扫码支付(用户扫商家二维码)
# wx_qr - 微信扫码支付(用户扫商家二维码)
# qq_qr - qq扫码支付(用户扫商家二维码)
# cardpay– 网银
# quick– 快捷
# alipay_h5  -支付宝H5
def _get_pay_type(service):
    if service == 'alipay':
        return 'alipay_h5'
    elif service == 'quick':
        return 'quick'
    return 'quick'


def gen_sign_str(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        # if parameter[k] != '' and parameter[k] != None:
        if parameter[k] != None:
            s += '%s=%s&' % (k, parameter[k])
    return s[0:len(s) - 1]


def gen_notify_sign_str(parameter):
    return 'amount={}&merNo={}&notifyUrl={}&orderDate={}&orderNo={}&payId={}&respCode={}&respDesc={}&transType={}'.format(
        parameter['amount'], parameter['merNo'], parameter['notifyUrl'], parameter['orderDate'], parameter['orderNo'],
        parameter['payId'], parameter['respCode'], parameter['respDesc'].encode('utf8'), parameter['transType']
    )


def generate_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['signature']
    calculated_sign = generate_sign(gen_notify_sign_str(params).decode('utf8') + key)
    if sign != calculated_sign:
        _LOGGER.info("e520pay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_str(s, start, end):
    p1 = s.index(start)
    p2 = s.index(end, p1 + len(start))
    if p2 > p1:
        return s[p1 + len(start): p2]
    else:
        return


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')
    parameter_dict = OrderedDict((
        # ('version', 'V4.0'),
        ('channel', _get_pay_type(service)),
        ('transType', '01'),
        ('merNo', app_id),
        ('orderDate', time.strftime("%Y%m%d")),
        ('orderNo', str(pay.id)),
        ('returnUrl', '{}/pay/api/{}/e520pay/{}/'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyUrl', '{}/pay/api/{}/e520pay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('amount', str(int(pay_amount * 100))),
        ('goodsInf', 'charge'),
    ))
    s = gen_sign_str(parameter_dict)
    parameter_dict['signature'] = generate_sign(s + api_key)
    parameter_dict['version'] = 'V4.0'
    _LOGGER.info("e520pay create  data: %s", parameter_dict)
    html = _build_form(parameter_dict)
    cache_id = redis_cache.save_html(pay.id, html)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


# SUCCESS
def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("e520pay notify data: %s", data)
    _LOGGER.info("e520pay notify body: %s", request.body)
    verify_notify_sign(data, api_key)
    pay_id = data['orderNo']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('e520pay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['respCode'])
    trade_no = data['payId']
    total_fee = float(data['amount']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0000':
        _LOGGER.info('e520pay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    # prepare param
    # 暂未提供
    pass


if __name__ == '__main__':
    app_id = '100110089991188'
    api_key = _get_api_key(app_id)
    d = {u'payId': u'200023003200', u'respCode': u'0000',
         u'notifyUrl': u'http://219.135.56.195:9003/pay/api/third/notify/e520pay/100110089991188', u'transType': u'10',
         u'orderDate': u'20180129', u'respDesc': u'\u4ea4\u6613\u6210\u529f', u'amount': u'100',
         u'signature': u'B5595390665DAC9A2D4825421D3F4628', u'payTime': u'20180129111754', u'merNo': u'100110089991188',
         u'orderNo': u'1629076546815788032'}
    s = gen_notify_sign_str(d)
    print s
    sign = generate_sign(s.decode('utf8') + api_key)
    print sign
